<?php

class Url
{
	private $_url = null;
	
	public function __construct($url = null)
	{
		if ($url instanceof Url) {
			$url = $url->asString();
		}

		if (empty($url)) $url = '/';
		$this->_url = $url;
	}
	
	public function __toString()
	{
		return (string) $this->_url;
	}
	
	public function getParts()
	{		
		$parts = explode('/', $this->_url);
		if (empty($parts[count($parts) - 1])) {
			array_pop($parts);
		}
		
		return $parts;
	}
	
	public function append($str)
	{
		$parts = $this->getParts();
		$parts[] = $str;
		
		$this->_url = implode('/', $parts);
		return $this->_url;
	}
	
	public function prepend($str)
	{
		$parts = $this->getParts();
		array_unshift($parts, $str);
		
		$this->_url = '/' . implode('/', $parts);
		return $this->_url;
	}	
	
	public function changePart($idx, $new)
	{
		$parts = $this->getParts();
		
		if ($idx == 0) {
			return $this->prepend($new);
			
		} else if ($idx == count($parts)) {
			return $this->append($new);
			
		} else if ($idx > 0 && $idx < count($parts)) {			
			$parts[$idx] = $new;	
		}		
		
		$this->_url = implode('/', $parts);
		return $this->_url;
	}
	
	public function deleteParts($idx)
	{
		$parts = $this->getParts();
		
		if (is_integer($idx) && ($idx <= 0 || $idx >= count($parts))) {
			return $this->_url;
		} else if (!is_array($idx)) {
			$idx = array($idx);
		}
						
		$tmp = array();
		foreach($parts as $k => $v) {
			if (!in_array($k, $idx)) {
				$tmp[] = $v;
			}
		}
		
		$parts = $tmp;
		
		$this->_url = implode('/', $parts);
		return $this->_url;	
	}
}